//
//  ProductListModel.m
//  DA_V
//
//  Created by 中亿世联前台 on 15/5/14.
//  Copyright (c) 2015年 zhouhai. All rights reserved.
//

#import "ProductListModel.h"
#import "AFNetworking.h"
#import "InterFace.h"
#import "EncryptionData.h"
#import "ProductModel.h"
#import "CategoryModel.h"
#import "JSONKit.h"

@implementation ProductListModel
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{}

#pragma -mark 向服务器根据Tag获取相应的商品列表
- (void)getProductList:(NSMutableArray *)array parameter:(NSDictionary *)parameter{
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript",@"text/plain", nil];
    
    
//    NSMutableArray *parameterArray = [[NSMutableArray alloc]init];
//    @property (nonatomic,copy) NSString *ProductID;  //产品ID
//    @property (nonatomic,copy) NSString *ThumbPath;  //产品缩略图
//    @property (nonatomic,copy) NSString *ProductName;//产品名称
//    NSString *agentId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
//    NSDictionary *parameterDic = @{@"TagName":parameter.ProductName,@"AgentID":agentId};
    
//    [parameterArray addObject:parameterDic];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameter options:NSJSONWritingPrettyPrinted error:nil];
    
    
    NSString *jsonString = [jsonData base64EncodedStringWithOptions:0];
    
    EncryptionData *enctytion = [[EncryptionData alloc] init];
    
    NSString *str = [enctytion encodeString:jsonString:PasswordKey];
 
    NSDictionary *paramer = @{@"sign":str};

    [manager POST:GetProductListInterface parameters:paramer success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *dic =  [NSJSONSerialization  JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
         
    
        
        NSString *str = dic[@"sign"];
        
        
        EncryptionData *data = [[EncryptionData alloc]init];
        NSString *datastr = [data decryption:str :PasswordKey];
        
        NSData* dataFromString = [datastr dataUsingEncoding:NSUTF8StringEncoding];
        
        NSDictionary *dataDic = [NSJSONSerialization  JSONObjectWithData:dataFromString options:NSJSONReadingMutableContainers error:nil];
        
        //返回成功
        if ( [[dataDic objectForKey:@"status"] isEqualToString:@"success"]) {
            
            NSLog(@"返回结果 ＝＝＝＝ %@",dataDic);
            NSArray *myDatArr =dataDic[@"data"];
            //
            for (int i = 0; i <[myDatArr count]; i++) {
                //
                NSDictionary *productDic = myDatArr[i];
                ProductListModel *model = [[ProductListModel alloc] init];
                //
                [model setValuesForKeysWithDictionary:productDic];
                //
                [array addObject:model];
            }
            [self.productlistModelDelegate getProDuctListInterfaceEnd];
        }  else if ( [[dataDic objectForKey:@"status"] isEqualToString:@"failed"]) {
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[dataDic objectForKey:@"reason"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
            [self.productlistModelDelegate getrequesterror:[dataDic objectForKey:@"reason"]];
        } else{
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"服务器异常,无法加载数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
            [self.productlistModelDelegate getrequesterror:@"服务器异常"];

        }

        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.productlistModelDelegate requesterror];
//        NSLog(@"========== %@", [error description]);
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"网络异常,无法加载数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alert show];
        
    }];
    
}


#pragma -mark 向服务器更具类型获取相应的商品列表
- (void)getCategoryList:(NSMutableArray *)array parameter:(NSDictionary *)parameter{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    //    NSMutableArray *parameterArray = [[NSMutableArray alloc]init];
//    NSString *agentId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
    @try {
//        NSDictionary *parameterDic = @{@"AgentID":agentId,@"CategoryID":parameter.CategoryID};
        //    [parameterArray addObject:parameterDic];
        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameter options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonString = [jsonData base64EncodedStringWithOptions:0];
        //EncryptionData *enctytion = [[EncryptionData alloc] init];
        NSString *str = [self encodeString:jsonString key:PasswordKey];
        
        NSDictionary *paramer = @{@"sign":str};
  


    [manager POST:ProductListInterface parameters:paramer success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        // NSDictionary *dic =  [NSJSONSerialization  JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSString *str = responseObject[@"sign"];
        
        EncryptionData *data = [[EncryptionData alloc]init];
        NSString *datastr = [data decryption:str :PasswordKey];
        NSData* dataFromString = [datastr dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dataDic = [NSJSONSerialization  JSONObjectWithData:dataFromString options:NSJSONReadingMutableContainers error:nil];
        
        //返回成功
        if ( [[dataDic objectForKey:@"status"] isEqualToString:@"success"]) {
            
            NSLog(@"返回结果 ＝＝＝＝ %@",dataDic);
            NSArray *myDatArr =dataDic[@"data"];
            //
            for (int i = 0; i <[myDatArr count]; i++) {
                //
                NSDictionary *productDic = myDatArr[i];
                ProductListModel *model = [[ProductListModel alloc] init];
                //
                [model setValuesForKeysWithDictionary:productDic];
                //
                [array addObject:model];
            }
            [self.productlistModelDelegate getCategoryListInterfaceEnd];
        } else  if ( [[dataDic objectForKey:@"status"] isEqualToString:@"failed"]){
//                [self.productlistModelDelegate getCategoryListInterfaceEnd];
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[dataDic objectForKey:@"reason"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
              [self.productlistModelDelegate getrequesterror:[dataDic objectForKey:@"reason"]];
        } else{
//            [self.productlistModelDelegate getCategoryListInterfaceEnd];
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"服务器异常,无法加载数据"delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
                   [self.productlistModelDelegate getrequesterror:@""];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//            [self.productlistModelDelegate getCategoryListInterfaceEnd];
//        NSLog(@"========== %@", [error description]);
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"网络异常,无法加载数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alert show];
                [self.productlistModelDelegate requesterror];
        
    }];
    }
    @catch (NSException *exception) {
        
        NSLog(@"商品列表页抛出异常 ＝＝＝＝＝ %@",[exception userInfo]);
    }
}
#pragma mark - 加密
-(NSString *)encodeString:(NSString *)data  key:(NSString *)key{
    //    NSData* sampleData = [data dataUsingEncoding:NSUTF8StringEncoding];
    //
    //    NSString * base64String = [sampleData base64EncodedStringWithOptions:0];
    NSLog(@"%@",data);
    NSString *result=[[NSMutableString alloc] init];
    NSInteger keyLength = [key length];
    int position = 0;
    int keyChar = 0;
    int strChar = 0;
    for (int i = 0; i < [data length]; i++) {
        position = i % keyLength;
        strChar = [data characterAtIndex:i];
        keyChar =[key characterAtIndex:position];
        int  ch = strChar ^ keyChar;
        char ca = (char) ch;
        result=[result stringByAppendingString:[NSString stringWithFormat:@"%C",ca]];
    }
    
    NSData* sampleDat1a = [result dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString * base64String1 = [sampleDat1a base64EncodedStringWithOptions:0];
    
    return base64String1;
}


@end
